package com.tool.shiro.dao.impl;

import com.tool.shiro.dao.ShiroAdminDao;
import com.tool.shiro.pojo.ShiroAdminManage;
import com.tool.shiro.util.CommonUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 数据库操作具体实现类
 * SQLTemplate: SQL语句模板
 * SQL: 真正执行的SQL语句
 * 注: SQL注入等问题待调试和解决
 */
@Repository
@Mapper
public class ShiroAdminDaoImpl implements ShiroAdminDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public ShiroAdminManage findByAccount(String account) {
        String sqlTemplate = "SELECT id, account, password, salt FROM shiro_admin_manage WHERE account = ";
        String SQL = sqlTemplate + account;
        try {
            return (ShiroAdminManage) CommonUtils.getDtoObject(jdbcTemplate.queryForMap(SQL), ShiroAdminManage.class);
        }catch (BadSqlGrammarException e) {
            System.out.println("查询参数为空");
            e.printStackTrace();
        }catch (Exception e) {
            System.out.println("错误");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean findAccountIsExist(String account) {
        String SQL = "SELECT count(*) FROM shiro_admin_manage WHERE account = ?";
        try {
            if (jdbcTemplate.queryForObject(SQL, new java.lang.Object[]{account}, Integer.class) < 1) {
                return false;
            }
        }catch (Exception e) {
            System.out.println("错误");
        }
        return  true;
    }

    @Override
    public int insertShiroAdmin(ShiroAdminManage shiroAdmin) {
        String sqlTemplate = "INSERT INTO shiro_admin_manage (account, `password`, salt) VALUES (?, ?, ?);";
        try {
            return jdbcTemplate.update(con -> {
                PreparedStatement preparedStatement = con.prepareStatement(sqlTemplate);
                preparedStatement.setString(1, shiroAdmin.getAccount());
                preparedStatement.setString(2, shiroAdmin.getPassword());
                preparedStatement.setString(3, shiroAdmin.getSalt());
                return preparedStatement;
            });
        }catch (DuplicateKeyException e) {
            System.out.println("表中已存在该account账号");
        }catch (Exception e) {
            System.out.println("未知错误");
        }
        return 0;
    }


    @Override
    public Map<String, Object> getDataBaseInfo() throws SQLException {
        Map<String, String> database = new HashMap<>();
        database.put("catalog", Objects.requireNonNull(jdbcTemplate.getDataSource()).getConnection().getCatalog());
        database.put("databaseProductName", Objects.requireNonNull(jdbcTemplate.getDataSource()).getConnection().getMetaData().getDatabaseProductName());
        database.put("url", Objects.requireNonNull(jdbcTemplate.getDataSource()).getConnection().getMetaData().getURL());
        database.put("databaseMajorVersion", String.valueOf(jdbcTemplate.getDataSource().getConnection().getMetaData().getDatabaseMajorVersion()));
        database.put("databaseProductVersion", Objects.requireNonNull(jdbcTemplate.getDataSource()).getConnection().getMetaData().getDatabaseProductVersion());
        DatabaseMetaData databaseMetaData = jdbcTemplate.getDataSource().getConnection().getMetaData();
        ResultSet tables = databaseMetaData.getTables(jdbcTemplate.getDataSource().getConnection().getCatalog(), null, null, null);
        List<Map<String, String>> tableList = new ArrayList<>();
        // 显示指定表
        List<String> showTables = new ArrayList<>();
        showTables.add("shiro_user");
        showTables.add("shiro_user_role");
        showTables.add("shiro_role");
        showTables.add("shiro_role_permission");
        showTables.add("shiro_resource");
        showTables.add("shiro_permission");
        showTables.add("shiro_admin_manage");
        showTables.add("shiro_config_manage");
        while (tables.next()) {
            Map<String, String> map = new HashMap<>();
            // 只显示指定表格,需要显示全部表时将该if判断去掉
            if (showTables.contains(tables.getString("TABLE_NAME"))) {
                map.put("name", tables.getString("TABLE_NAME"));
                map.put("type", tables.getString("TABLE_TYPE"));
                map.put("remarks", tables.getString("REMARKS"));
                tableList.add(map);
            }
        }
        Map<String, Object> map = new HashMap<>();
        if (!database.isEmpty()) {
            map.put("database", database);
        }if (tableList.size() > 1) {
            map.put("tables", tableList);
        }
        return map;
    }

}
